#!/usr/bin/env python
#-*- coding:utf-8 -*-
from . import db, login_manager
from flask_login import UserMixin, AnonymousUserMixin
from datetime import datetime
from markdown import markdown
#from passlib.apps import custom_app_context as pwd_context
from werkzeug.security import generate_password_hash, check_password_hash


class Role(db.Model):
    __tablename__ ='roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=True)
    useres = db.relationship('User', backref='role')

    @staticmethod
    def seed():
        db.session.add_all(map(lambda r: Role(name=r), ['Guests', 'Administrators']))
        db.session.commit()


class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=True)
    realname = db.Column(db.String(20), nullable=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    #posts = db.relationship('Post', backref='author')
    #comments = db.relationship('Comment', backref='author')
    dailys = db.relationship('Daily', backref='author')

    @staticmethod
    def on_created(target, value, oldvalue,initiator):
        target.role = Role.query.filter_by(name='Guests').first()

    # def hash_password(self, password):
    #     self.password_hash = pwd_context.encrypt(password)
    #
    # def verify_password(self, password):
    #     return pwd_context.verify(password, self.password)

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verity_password(self, password):
        return check_password_hash(self.password_hash, password)


class AnonymousUser(AnonymousUserMixin):
    def is_administrator(self):
        return False


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

db.event.listen(User.name, 'set', User.on_created)


class Daily(db.Model):
    __tablename__ = 'dailys'
    id = db.Column(db.Integer, primary_key=True)
    item = db.Column(db.String(200))
    detail = db.Column(db.String(200))
    status = db.Column(db.String(100))
    #finsh_time = db.Column(db.DateTime,default=datetime.utcnow)
    finsh_time = db.Column(db.String(20))
    desc = db.Column(db.String(200))
    created = db.Column(db.DateTime, index=True, default=datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
